{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Item('bar')\n",
      "Item('spam')\n",
      "Item('foo')\n",
      "Item('grok')\n"
     ]
    }
   ],
   "source": [
    "import heapq\n",
    "class PriorityQueue:\n",
    "    \n",
    "    def __init__(self):\n",
    "        self._queue = []\n",
    "        self._index = 0\n",
    "    \n",
    "    def push(self, item, priority):\n",
    "        heapq.heappush(self._queue, (-priority, self._index, item))\n",
    "        self._index += 1\n",
    "\n",
    "    def pop(self):\n",
    "        return heapq.heappop(self._queue)[-1]\n",
    "    \n",
    "# 使用案例\n",
    "\n",
    "class Item:\n",
    "    \n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "    def __repr__(self):\n",
    "        return 'Item({!r})'.format(self.name)\n",
    "\n",
    "q = PriorityQueue()\n",
    "q.push(Item('foo'), 1)\n",
    "q.push(Item('bar'), 5)\n",
    "q.push(Item('spam'), 4)\n",
    "q.push(Item('grok'), 1)\n",
    "print(q.pop())\n",
    "print(q.pop())\n",
    "print(q.pop())\n",
    "print(q.pop())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**上例中使用heapq堆顶为最小值这个特性，把优先级作为第一个大小判定参考；\n",
    "<br>\n",
    "在优先级相同的情况下，则根据插入顺序进行优先判定；**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.7.4 64-bit",
   "language": "python",
   "name": "python37464bit0eab7a6caf29454899b876d50238c56e"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
